<template>
    <div>
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>

        <el-card>
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-input placeholder="请输入内容" v-model="user.name" clearable @clear="serachUserByPageInfo()">

                        <el-button slot="append" icon="el-icon-search" @click="seachUser()"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="6">
                    <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
                </el-col>


                <el-table :data="userList" style="width: 100%" border row-key="id">
                    <el-table-column type="index" label="序号" width="180">
                    </el-table-column>
                    <el-table-column prop="name" label="姓名" width="180">
                    </el-table-column>
                    <el-table-column prop="age" label="年纪" width="180">
                    </el-table-column>
                    <el-table-column prop="token" label="token">
                    </el-table-column>

                    <el-table-column label="状态">
                        <template slot-scope="scope">
                            <el-switch v-model="scope.row.swtich" :active-value="'1'" :inactive-value="'0'"
                                @change="handleSwitch(scope.row)">
                            </el-switch>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <!-- 修改 -->

                            <el-button type="primary" icon="el-icon-edit" circle
                                @click="updateUser(scope.row)"></el-button>

                            <!--删除 -->
                            <el-button type="danger" icon="el-icon-delete" circle
                                @click="deleteUser(scope.row)"></el-button>



                            <el-tooltip class="item" effect="dark" content="给用户设置角色" placement="top-start"
                                :enterable="false">
                                <!-- 给用户分配角色 -->
                                <el-button type="info" icon="el-icon-setting" circle
                                    @click="asinRole(scope.row)"></el-button>
                            </el-tooltip>
                        </template>


                    </el-table-column>

                </el-table>
            </el-row>

            <!-- 分页 -->
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :page-sizes="[10, 20, 30, 40]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </el-card>

        <!-- 添加用户 -->
        <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%" @closed="addFormClose">
            <el-form :model="addForm" status-icon :rules="rules" ref="addFormRef" label-width="100px"
                class="demo-ruleForm">
                <el-form-item label="姓名" prop="name">
                    <el-input type="text" v-model="addForm.name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="年纪" prop="age">
                    <el-input type="text" v-model="addForm.age" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="token" prop="token">
                    <el-input type="text" v-model="addForm.token"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm()">提交</el-button>
                    <el-button @click="dialogVisible = false"> 取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

        <!-- 修改用户 -->
        <el-dialog title="修改用户" :visible.sync="dialogVisibleUpdate" width="50%" @closed="addFormClose">
            <el-form :model="updateForm" status-icon :rules="rules" ref="addFormRef" label-width="100px"
                class="demo-ruleForm">
                <el-form-item label="姓名" prop="name">
                    <el-input type="text" autocomplete="off" v-model="updateForm.name"></el-input>
                </el-form-item>
                <el-form-item label="年纪" prop="age">
                    <el-input type="text" autocomplete="off" v-model="updateForm.age"></el-input>
                </el-form-item>
                <el-form-item label="token" prop="token">
                    <el-input type="text" v-model="updateForm.token"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="updateFormMethod()">修改用户</el-button>
                    <el-button @click="dialogVisibleUpdate = false"> 取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>



        <!-- 分配角色 -->
        <el-dialog title="分配角色" :visible.sync="asignRole" width="50%" @close="handleRoleTree()">

            <el-tree :props="props" show-checkbox :data="roleList" ref="roleRef" node-key="id"
                :default-checked-keys="defKey">
            </el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="asignRole = false">取 消</el-button>
                <el-button type="primary" @click="editRole()">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import { students, updateStatus, addStudent, updateStudent, deleteStudent, updateUserRole, getRoleIdByUserId } from '@/api/index.js';


import { getRoleList } from '@/api/Permission.js'
export default
    {

        name: "userList",

        data() {




            //校验邮箱
            var validatePass2 = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入邮箱名字'));
                } else {
                    // 正则表达式模式
                    const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;

                    if (!emailRegex.test(value)) {
                        callback(new Error('邮箱不正确'));
                    } else {
                        callback();
                    }
                }


            };


            return {
                //角色对话框显示
                asignRole: false,
                //角色数数据展示
                roleList: [],

                //正在操作的用户节点
                slectUserNode: {},

                //选中的节点
                defKey: [],

                props: {
                    label: 'name'
                },
                user: { pageNum: 1, 'pageSize': 10, name: '' },
                userList: [],
                total: 10,
                pageSize: 10,
                //展示隐藏对话框
                dialogVisible: false,
                addForm: { name: '', age: '', token: '' },

                updateForm: { name: '', age: '', token: '', id: '' },
                // 修改用户对话框
                dialogVisibleUpdate: false,
                rules: {
                    name: [
                        { required: true, message: '请输入名字', trigger: 'blur' },
                        { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                    ],
                    age: [
                        { required: true, message: '请输入年纪', trigger: 'blur' }
                    ], token: [

                        { validator: validatePass2, trigger: 'blur' }
                    ]
                }
            };
        }

        ,

        methods: {
            handleSizeChange(val) {
                console.log(`每页 ${val} 条`);
                this.user.pageNum = val;
                students(this.user).then(async (res) => {
                    this.userList = res.data.data.list
                    this.total = res.data.data.total
                })
            },
            handleCurrentChange(val) {
                console.log(`当前页: ${val}`);
                this.user.pageNum = val;
                this.serachUserByPageInfo();

            }, handleSwitch(val) {
                console.log("修改用户状态", val);
                updateStatus(val);
                students(this.user)

            }, seachUser() {
                this.serachUserByPageInfo()
            }, serachUserByPageInfo() {
                students(this.user).then((res) => {
                    this.userList = res.data.data.list
                    this.total = res.data.data.total
                })
            },
            //提交用户
            submitForm() {
                // 进行表单校验
                this.$refs.addFormRef.validate((valid) => {

                    console.log("nn", valid)
                    // 校验通过
                    if (valid) {
                        // 调用添加用户接口
                        addStudent(this.addForm)
                            .then(() => {
                                // 显示成功提示
                                this.$message.success('添加用户成功');
                                // 关闭对话框
                                this.dialogVisible = false;
                                // 重新加载用户列表
                                this.serachUserByPageInfo();
                            })
                            .catch(() => {
                                // 显示失败提示
                                this.$message.error('添加用户失败');
                            });
                    } else {
                        // 校验失败，显示提示
                        this.$message.error('表单校验失败，请检查输入内容');
                        // 不关闭对话框，返回
                        return false;
                    }
                });


                this.dialogVisible = false;

            }, //关闭对话框的回调
            addFormClose() {
                console.log('关闭前：', this)
                this.$refs.addFormRef.resetFields();
            },
            updateUser(row) {
                console.log('row', row)
                this.dialogVisibleUpdate = true;
                this.updateForm.name = row.name;
                this.updateForm.age = row.age;
                this.updateForm.token = row.token;
                this.updateForm.id = row.id;
            }, updateFormMethod() {
                this.$refs.addFormRef.validate(async (valid) => {
                    if (valid) {
                        // 等待更新接口完成
                        await updateStudent(this.updateForm);
                        this.$message.success('修改成功');
                        this.dialogVisibleUpdate = false;
                        //刷新页面
                        this.serachUserByPageInfo();
                    }

                })
            }, deleteUser(row) {
                console.log('del', row)
                this.$confirm('是否删除用户' + row.name + '', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    deleteStudent(row)
                    //刷新页面
                    this.serachUserByPageInfo();

                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            }, async asinRole(row) {

                console.log("用户节点{}", row)
                this.asignRole = true;
                let role = { pageNum: 1, pageSize: 1000 };

                await getRoleList(role).then(res => {


                    this.roleList = res.data.data.list;
                })
                this.slectUserNode = row;


                console.log("选中的节点{}", row);

                let roleParm = { id: row.id }

                await getRoleIdByUserId(roleParm).then((res) => {
                    this.defKey = res.data.data

                })


            }, editRole() {

                let roleIds = this.$refs.roleRef.getCheckedNodes().map(item => item.id);

                console.log("选中的节点{}", roleIds)
                //修改用户角色关联
                let userRole = { userId: this.slectUserNode.id, roleIdList: roleIds };

                updateUserRole(userRole);
                this.asignRole = false;

            }, handleRoleTree() {
                console.log("清楚节点")
                this.defKey = [];
            }

        },
        created() {
            students(this.user).then(async (res) => {
                this.userList = res.data.data.list
                this.total = res.data.data.total
            })


        }
    }



// 在此添加组件的其他逻辑
</script>
<style scoped>
/* 在此添加组件的样式 */

.el-card {
    margin-top: 20px;

}

.el-table {
    margin-top: 60px;
}

.el-pagination {
    display: flex;
    justify-content: center;
}
</style>